package com.luke.zuul.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * 资源服务配置
 */
@Configuration
public class ResourceServerConfig{

    /**代表了当前服务的ID，客户端必须拥有该资源才能访问该服务*/
    public static final String RESOURCE_ID = "res1";

    //管理每一个资源服务
    @Configuration
    @EnableResourceServer
    public class  AuthServerConfig extends ResourceServerConfigurerAdapter{

        @Autowired
        private TokenStore tokenStore;

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
            resources.tokenStore(tokenStore)
                    .resourceId(RESOURCE_ID)
                    .stateless(true);
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            //对访问认证服务的全部通过
            http.authorizeRequests().antMatchers("/auth-service/**").permitAll();
        }
    }

    @Configuration
    @EnableResourceServer
    public class  OrderServiceConfig extends ResourceServerConfigurerAdapter{

        @Autowired
        private TokenStore tokenStore;

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
            resources.tokenStore(tokenStore)
                    .resourceId(RESOURCE_ID)
                    .stateless(true);
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            //需要具备对应的scope才可以访问
            http.authorizeRequests()
                    .antMatchers("/order-service/**")
                    .access("#oauth2.hasScope('ROLE_API')");//TODO 似乎使用一个XxxConfig即可？
        }
    }

}
